﻿using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using NLog;

namespace Labthink.PCSoft.UniversalHost4.Utility
{
    /// 串口辅助类
    public class SerialPortExtend
    {
        /// 接收事件是否有效 false表示有效
        public bool ReceiveEventFlag;

        /// 完整协议的记录处理事件
        public event DataReceivedEventHandler DataReceived;
        public event SerialErrorReceivedEventHandler Error;
        private readonly Logger _logger = LogManager.GetCurrentClassLogger();

        private readonly SerialPortBaudRates _baudRate;

        private readonly SerialPort _comPort = new SerialPort();

        /// <summary>
        /// 串口号
        /// </summary>
        public string PortName { get; set; }

        /// <summary>
        /// 数据位
        /// </summary>
        public SerialPortDataBits DataBits { get; set; }

        /// <summary>
        /// 奇偶校验位
        /// </summary>
        public Parity Parity { get; set; }

        /// <summary>
        /// 停止位
        /// </summary>
        public StopBits StopBits { get; set; }

        /// 参数构造函数（使用枚举参数构造）
        /// <param name="name">串口号</param>
        /// <param name="baud">波特率</param>
        /// <param name="dBits">数据位</param>
        /// <param name="par">奇偶校验位</param>
        /// <param name="sBits">停止位</param>
        public SerialPortExtend(string name, SerialPortBaudRates baud, SerialPortDataBits dBits, Parity par, StopBits sBits)
        {
            PortName = name;
            _baudRate = baud;
            DataBits = dBits;
            Parity = par;
            StopBits = sBits;

            _comPort.DataReceived += comPort_DataReceived;
            _comPort.ErrorReceived += comPort_ErrorReceived;
        }

        /// <summary>
        /// 参数构造函数（使用枚举参数构造）
        /// </summary>
        /// <param name="name"></param>
        public SerialPortExtend(string name)
        {
            PortName = name;
            _baudRate = SerialPortBaudRates.BaudRate9600;
            DataBits =  SerialPortDataBits.EightBits;
            Parity = Parity.None;
            StopBits = StopBits.One;

            _comPort.DataReceived += comPort_DataReceived;
            _comPort.ErrorReceived += comPort_ErrorReceived;
        }

        /// 参数构造函数（使用字符串参数构造）
        /// <param name="name">串口号</param>
        /// <param name="baud">波特率</param>
        /// <param name="dBits">数据位</param>
        /// <param name="par">奇偶校验位</param>
        /// <param name="sBits">停止位</param>
        public SerialPortExtend(string name, string baud, string dBits, string par, string sBits)
        {
            PortName = name;
            _baudRate = (SerialPortBaudRates)Enum.Parse(typeof(SerialPortBaudRates), baud);
            DataBits = (SerialPortDataBits)Enum.Parse(typeof(SerialPortDataBits), dBits);
            Parity = (Parity)Enum.Parse(typeof(Parity), par);
            StopBits = (StopBits)Enum.Parse(typeof(StopBits), sBits);

            _comPort.DataReceived += comPort_DataReceived;
            _comPort.ErrorReceived += comPort_ErrorReceived;
        }

        public SerialPortExtend()
        {
            PortName = "COM1";
            _baudRate = SerialPortBaudRates.BaudRate9600;
            DataBits = SerialPortDataBits.EightBits;
            Parity = Parity.None;
            StopBits = StopBits.One;
            _comPort.DataReceived += comPort_DataReceived;
            _comPort.ErrorReceived += comPort_ErrorReceived;
        }

        /// <summary>
        /// 端口是否已经打开
        /// </summary>
        public bool IsOpen => _comPort.IsOpen;

        public void SetReceivedBytesThreshold(int rBytesThreshold)
        {
            _comPort.ReceivedBytesThreshold = rBytesThreshold;
        }

        /// <summary>
        /// 打开端口
        /// </summary>
        /// <returns></returns>
        public bool OpenPort()
        {
            if (_comPort.IsOpen) _comPort.Close();

            _comPort.PortName = PortName;
            _comPort.BaudRate = (int)_baudRate;
            _comPort.DataBits = (int)DataBits;
            _comPort.Parity = Parity;
            _comPort.StopBits = StopBits;

            try
            {
                _comPort.Open();
                return true;
            }
            catch (Exception ex)
            {
                _logger.Error(ex.Message);
                return false;
            }
        }

        /// <summary>
        /// 关闭端口
        /// </summary>
        public void ClosePort()
        {
            if ( _comPort != null &&_comPort.IsOpen)
                _comPort.Close();
        }

        /// 丢弃来自串行驱动程序的接收和发送缓冲区的数据
        public void DiscardBuffer()
        {
            _comPort.DiscardInBuffer();
            _comPort.DiscardOutBuffer();
        }

        /// <summary>
        /// 数据接收处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void comPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            //禁止接收事件时直接退出
            if (ReceiveEventFlag) return;
            try
            {
                var readBuffer = new byte[_comPort.BytesToRead];
                _comPort.Read(readBuffer, 0, readBuffer.Length);
                //触发整条记录的处理
                DataReceived?.Invoke(new DataReceivedEventArgs(readBuffer));
                Thread.Sleep(10);
            }
            catch (Exception ee)
            {
                _logger.Error("串口数据读取错误 " + ee.Message);
            }
        }

        /// <summary>
        /// 错误处理函数
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void comPort_ErrorReceived(object sender, SerialErrorReceivedEventArgs e)
        {
            Error?.Invoke(sender, e);
        }

        /// 写入数据
        public void WriteData(string msg)
        {
            if (!_comPort.IsOpen) _comPort.Open();

            _comPort.Write(msg);
        }

        /// <summary>
        /// 写入数据
        /// </summary>
        /// <param name="msg">写入端口的字节数组</param>
        public void WriteData(byte[] msg)
        {
            if (!_comPort.IsOpen)
            {
               _logger.Error("串口未打开，可能被占用或者硬件损坏");
               return;
            }

            _comPort.Write(msg, 0, msg.Length);
        }

        /// <summary>
        /// 写入数据
        /// </summary>
        /// <param name="msg">包含要写入端口的字节数组</param>
        /// <param name="offset">参数从0字节开始的字节偏移量</param>
        /// <param name="count">要写入的字节数</param>
        public void WriteData(byte[] msg, int offset, int count)
        {
            if (!_comPort.IsOpen) _comPort.Open();

            _comPort.Write(msg, offset, count);
        }

        /// <summary>
        /// 发送串口命令
        /// </summary>
        /// <param name="sendData">发送数据</param>
        /// <param name="receiveData">接收数据</param>
        /// <param name="overtime">重复次数</param>
        /// <returns></returns>
        public int SendCommand(byte[] sendData, ref byte[] receiveData, int overtime)
        {
            if (!_comPort.IsOpen) _comPort.Open();

            ReceiveEventFlag = true;        //关闭接收事件
            _comPort.DiscardInBuffer();      //清空接收缓冲区
            _comPort.Write(sendData, 0, sendData.Length);

            int num = 0, ret = 0;
            while (num++ < overtime)
            {
                if (_comPort.BytesToRead >= receiveData.Length) break;
                Thread.Sleep(1);
            }

            if (_comPort.BytesToRead >= receiveData.Length)
            {
                ret = _comPort.Read(receiveData, 0, receiveData.Length);
            }

            ReceiveEventFlag = false;       //打开事件
            return ret;
        }

        /// <summary>
        /// 封装获取串口号列表
        /// </summary>
        /// <returns></returns>
        public static string[] GetPortNames()
        {
            return SerialPort.GetPortNames();
        }

        /// <summary>
        /// 设置串口号
        /// </summary>
        /// <param name="obj"></param>
        public static void SetPortNameValues(ComboBox obj)
        {
            obj.Items.Clear();
            foreach (string str in SerialPort.GetPortNames())
            {
                obj.Items.Add(str);
            }
        }

        /// <summary>
        /// 设置波特率
        /// </summary>
        public static void SetBaudRateValues(ComboBox obj)
        {
            obj.Items.Clear();
            foreach (SerialPortBaudRates rate in Enum.GetValues(typeof(SerialPortBaudRates)))
            {
                // ReSharper disable once SpecifyACultureInStringConversionExplicitly
                obj.Items.Add(((int)rate).ToString());
            }
        }

        /// <summary>
        /// 设置数据位
        /// </summary>
        public static void SetDataBitsValues(ComboBox obj)
        {
            obj.Items.Clear();
            foreach (SerialPortDataBits dataBit in Enum.GetValues(typeof(SerialPortDataBits)))
            {
                // ReSharper disable once SpecifyACultureInStringConversionExplicitly
                obj.Items.Add(((int)dataBit).ToString());
            }
        }

        /// <summary>
        /// 设置校验位列表
        /// </summary>
        public static void SetParityValues(ComboBox obj)
        {
            obj.Items.Clear();
            foreach (string str in Enum.GetNames(typeof(Parity)))
            {
                obj.Items.Add(str);
            }
            //foreach (Parity party in Enum.GetValues(typeof(Parity)))
            //{
            //    obj.Items.Add(((int)party).ToString());
            //}
        }

        /// <summary>
        /// 设置停止位
        /// </summary>
        public static void SetStopBitValues(ComboBox obj)
        {
            obj.Items.Clear();
            foreach (string str in Enum.GetNames(typeof(StopBits)))
            {
                obj.Items.Add(str);
            }
            //foreach (StopBits stopBit in Enum.GetValues(typeof(StopBits)))
            //{
            //    obj.Items.Add(((int)stopBit).ToString());
            //}   
        }

        /// <summary>
        /// 转换十六进制字符串到字节数组
        /// </summary>
        /// <param name="msg">待转换字符串</param>
        /// <returns>字节数组</returns>
        public static byte[] HexToByte(string msg)
        {
            msg = msg.Replace(" ", "");//移除空格

            //create a byte array the length of the
            //divided by 2 (Hex is 2 characters in length)
            var comBuffer = new byte[msg.Length / 2];
            for (int i = 0; i < msg.Length; i += 2)
            {
                //convert each set of 2 characters to a byte and add to the array
                comBuffer[i / 2] = Convert.ToByte(msg.Substring(i, 2), 16);
            }

            return comBuffer;
        }

        /// <summary>
        /// 转换字节数组到十六进制字符串
        /// </summary>
        /// <param name="comByte">待转换字节数组</param>
        /// <returns>十六进制字符串</returns>
        public static string ByteToHex(byte[] comByte)
        {
            var builder = new StringBuilder(comByte.Length * 3);
            foreach (byte data in comByte)
            {
                builder.Append(Convert.ToString(data, 16).PadLeft(2, '0').PadRight(3, ' '));
            }

            return builder.ToString().ToUpper();
        }

        /// 检查端口名称是否存在
        public static bool Exists(string portName)
        {
            return SerialPort.GetPortNames().Any(port => port == portName);
        }

        /// 格式化端口相关属性
        public static string Format(SerialPort port)
        {
            return $"{port.PortName} ({port.BaudRate},{port.DataBits},{port.StopBits},{port.Parity},{port.Handshake})";
        }
    }

    public delegate void DataReceivedEventHandler(DataReceivedEventArgs e);

    /// 串口数据位列表（5,6,7,8）
    public enum SerialPortDataBits
    {
        FiveBits = 5,
        SixBits = 6,
        SevenBits = 7,
        EightBits = 8
    }

    /// 串口波特率列表
    public enum SerialPortBaudRates
    {
        BaudRate75 = 75,
        BaudRate110 = 110,
        BaudRate150 = 150,
        BaudRate300 = 300,
        BaudRate600 = 600,
        BaudRate1200 = 1200,
        BaudRate2400 = 2400,
        BaudRate4800 = 4800,
        BaudRate9600 = 9600,
        BaudRate14400 = 14400,
        BaudRate19200 = 19200,
        BaudRate28800 = 28800,
        BaudRate38400 = 38400,
        BaudRate56000 = 56000,
        BaudRate57600 = 57600,
        BaudRate115200 = 115200,
        BaudRate128000 = 128000,
        BaudRate230400 = 230400,
        BaudRate256000 = 256000
    }

    public class DataReceivedEventArgs : EventArgs
    {
        public byte[] Data { get; set; }

        public DataReceivedEventArgs()
        {
            Data = null;
        }

        public DataReceivedEventArgs(byte[] data)
        {
            Data = data;
        }
    }
}
